use std::{fmt::Debug, io::Cursor, string};

use calamine::{open_workbook_from_rs,open_workbook_auto_from_rs, Data as CalDataType, DataType, Range, Reader, Xlsx};
use futures::future::FutureExt;
use js_sys::{Array, JSON};
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use web_sys::File;

#[derive(Debug, Serialize, Deserialize)]
struct SheetData {
    name: String,
    data: Vec<String>,
}

#[wasm_bindgen]
pub async fn read_excel(file: File) -> Result<Array, JsValue> {
    let array_buffer_future = JsFuture::from(file.array_buffer());
    let array_buffer = array_buffer_future
        .await
        .map_err(|e| format!("Failed to get array buffer: {:?}", e))?;
    let data = js_sys::Uint8Array::new(&array_buffer).to_vec();

    // 打开 Excel 工作簿
    // 使用 Cursor 包装字节切片
    let cursor = Cursor::new(data);

    // 打开 Excel 工作簿
    let mut workbook: Xlsx<_> =
    open_workbook_from_rs(cursor).map_err(|e| format!("Failed to open workbook: {:?}", e))?;

    // 创建结果数组

    let result = Array::new();
    // result.push(&JsValue::from(workbook.sheet_names().join(",")));
    // 遍历所有工作表
    for (sheet_name, range) in workbook.worksheets() {
        let sheet_data = Array::new();
        for row in range.rows() {
            let row_array = Array::new();
            for cell in row {
                let cell_value = match cell {
                    CalDataType::Float(s) => JsValue::from_f64(*s),
                    CalDataType::Int(i) => JsValue::from_f64(*i as f64),
                    CalDataType::String(i) => JsValue::from_str(i),
                    CalDataType::Bool(i) => JsValue::from_bool(*i),
                    CalDataType::DateTime(dt) => JsValue::from(dt.to_string()),
                    // calamine::DataType::Float(f) => JsValue::from(f),
                    // calamine::DataType::Int(i) => JsValue::from(i),
                    // calamine::DataType::Bool(b) => JsValue::from(b),
                    // calamine::DataType::DateTime(dt) => {
                    //     JsValue::from(dt.format("%Y-%m-%d %H:%M:%S").to_string())
                    // },
                    other => JsValue::from(other.to_string()),
                };
                row_array.push(&cell_value);
            }
            sheet_data.push(&row_array);
        }
        let sheet_array = Array::new();
        sheet_array.push(&JsValue::from(sheet_name));
        sheet_array.push(&sheet_data);
        result.push(&sheet_array);
    }

    Ok(result)
}
